package com.dstz.agilebpm.springcloud.auth.edge.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstz.agilebpm.springcloud.auth.edge.enums.ServiceProviderEnum;
import com.dstz.agilebpm.springcloud.auth.edge.vo.UserDetailVO;
import com.dstz.agilebpm.springcloud.auth.edge.vo.UserRoleVO;
import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.api.response.impl.ResultMsg;
import com.dstz.org.api.model.IUser;
import com.dstz.org.api.model.IUserRole;
import com.dstz.org.api.service.UserService;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 用户业务接口实现
 *
 * @author wacxhs
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 得到URL地址
     *
     * @param api 接口
     * @return 全路径url
     */
    private String getUrl(String api) {
        return "http://" + ServiceProviderEnum.ORG_SERVICE.getValue() + api;
    }

    /**
     * 断言调用成功
     *
     * @param resultMsg 结果响应
     */
    private void assertSuccess(ResultMsg<?> resultMsg) {
        if (!resultMsg.getIsOk()) {
            throw new BusinessException(resultMsg.getMsg());
        }
    }

    /**
     * 转换列表数据
     *
     * @param resultMsg 接口返回信息
     * @param <T>       类型
     * @return 转换列表数据
     */
    @SuppressWarnings("unchecked")
    private <T> List<T> convertListData(ResultMsg<?> resultMsg) {
        assertSuccess(resultMsg);
        if (resultMsg.getData() == null || !(resultMsg.getData() instanceof List)) {
            return null;
        }
        return (List<T>) resultMsg.getData();
    }

    @Override
    public IUser getUserById(String userId) {
        ParameterizedTypeReference<ResultMsg<UserDetailVO>> typeReference = new ParameterizedTypeReference<ResultMsg<UserDetailVO>>() {
        };
        ResultMsg<UserDetailVO> resultMsg = restTemplate.exchange(getUrl("/org/user/get"), HttpMethod.POST, new HttpEntity<>(ImmutableMap.of("id", userId)), typeReference).getBody();
        assertSuccess(resultMsg);
        return resultMsg.getData();
    }

    @Override
    public IUser getUserByAccount(String account) {
        String responseBody = restTemplate.postForEntity(getUrl("/org/user/listJson"), ImmutableMap.of("account_^VEQ", account), String.class).getBody();
        JSONObject pageResult = JSON.parseObject(responseBody);
        JSONArray rows = pageResult.getJSONArray("rows");
        if (rows == null || rows.isEmpty()) {
            return null;
        }
        return rows.getJSONObject(0).toJavaObject(UserDetailVO.class);
    }

    @Override
    public List<IUser> getUserListByGroup(String groupType, String groupId) {
        ParameterizedTypeReference<ResultMsg<List<UserDetailVO>>> typeReference = new ParameterizedTypeReference<ResultMsg<List<UserDetailVO>>>() {
        };
        ResultMsg<List<UserDetailVO>> resultMsg = restTemplate.exchange(getUrl("/org/userExtra/getUserListByGroup"), HttpMethod.POST, new HttpEntity<>(ImmutableMap.of("groupType", groupType, "groupId", groupId)), typeReference).getBody();
        return convertListData(resultMsg);
    }

    @Override
    public List<IUserRole> getUserRole(String userId) {
        ParameterizedTypeReference<ResultMsg<List<UserRoleVO>>> typeReference = new ParameterizedTypeReference<ResultMsg<List<UserRoleVO>>>() {
        };
        ResultMsg<List<UserRoleVO>> resultMsg = restTemplate.exchange(getUrl("/org/userExtra/getUserRole"), HttpMethod.POST, new HttpEntity<>(ImmutableMap.of("userId", userId)), typeReference).getBody();
        return convertListData(resultMsg);
    }
}
